package server

import (
	"context"
	"encoding/json"
	"log"
	"net/http"
	"time"

	"yx.io/qwq-ai/myComponent"
	"yx.io/qwq-ai/utils"
)

var (
	GSESSION_ID = "GSESSION_ID"
)

func StartHttpServer(addr string) {
	// 启动 HTTP 服务器
	log.Printf("HTTP服务器运行中，监听地址：%s", addr)
	go func() {
		mux := http.NewServeMux()
		mux.HandleFunc("/qwq-ai/chat", sseHandler)
		mux.HandleFunc("/qwq-ai/cache", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json;charset=utf-8")
			jsonStr, _ := json.Marshal(myComponent.SessionContainer)
			w.Write([]byte(jsonStr))
		})
		fs := http.FileServer(http.Dir("./static"))
		mux.Handle("/qwq-ai/", http.StripPrefix("/qwq-ai/", fs))
		mux.HandleFunc("/qwq-ai/history", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json;charset=utf-8")

			baseResponse := myComponent.BaseResponse{
				Code: 0,
				Msg:  "success",
			}
			cookie, err := r.Cookie(GSESSION_ID)
			if err == nil && cookie != nil {
				baseResponse.Data = myComponent.SessionContainer[cookie.Value]
			}
			jsonStr, _ := json.Marshal(baseResponse)
			w.Write(jsonStr)
		})
		mux.Handle("/", fs)
		log.Fatal(http.ListenAndServe(addr, filterHandler(mux)))
	}()
	select {} // 阻塞等待事件，不耗 CPU。
	// for {} // 死循环忙等，会把一条 P 跑满。
}

type IP string

const IPKey IP = "ip"

func filterHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		now := time.Now()
		ip := utils.GetIP(r)
		ctx := context.WithValue(r.Context(), IPKey, ip) //将ip放入context中
		next.ServeHTTP(w, r.WithContext(ctx))
		duration := time.Since(now)
		log.Printf("http-log:%s\t%s\tduration:%v", ip, r.URL.Path, duration)
	})
}
